package tables

import (
	"time"

	"mini-admin/internal/conf"
	"mini-admin/internal/open"
	v1 "mini-admin/internal/open/service/v1"

	// "github.com/Cluas/go-wechat/wechat"
	wechat "gitee.com/quantum-force/wxopen-api"
	"github.com/GoAdminGroup/go-admin/context"
	"github.com/GoAdminGroup/go-admin/modules/db"
	"github.com/GoAdminGroup/go-admin/plugins/admin/modules/parameter"
	"github.com/GoAdminGroup/go-admin/plugins/admin/modules/table"
)

// GetExternalWechatTemplate return the model from external data source.
func GetExternalWechatTemplate(ctx *context.Context) (externalTable table.Table) {

	externalTable = table.NewDefaultTable(table.DefaultConfig())

	info := externalTable.GetInfo().HideDetailButton().HideEditButton()
	info.AddField("模版ID", "id", db.Int).FieldSortable()
	info.AddField("版本号", "user_version", db.Varchar)
	info.AddField("描述", "user_desc", db.Varchar)
	info.AddField("创建时间", "create_time", db.Varchar)

	info.SetTable("external_wechat_template").
		SetTitle("微信模版库").
		SetDescription("微信小程序模版库").
		SetGetDataFn(func(param parameter.Parameters) ([]map[string]interface{}, int) {
			res := make([]map[string]interface{}, 0)
			client := wechat.NewClient(nil)
			openClient := open.New(conf.Conf.OpenAddress)
			resp, err := openClient.ComponentAccessToken(ctx.Request.Context(), &v1.ComponentAccessTokenRequest{
				Platform: v1.Platform_PLATFORM_WECHAT,
				AppId:    conf.Conf.WechatAppID,
			})
			if err != nil {
				return nil, 0
			}
			templateList, _, err := client.WXA.GetTemplateList(ctx.Request.Context(), resp.ComponentAccessToken)
			if err != nil {
				return nil, 0
			}
			for _, template := range templateList.TemplateList {
				res = append(res, map[string]interface{}{
					"id":           template.TemplateID,
					"user_version": template.UserVersion,
					"user_desc":    template.UserDesc,
					"create_time":  time.Unix(int64(template.CreateTime), 0).Format(time.RFC3339),
				})
			}

			return res, len(templateList.TemplateList)
		}).SetDeleteFn(func(ids []string) error {
		client := wechat.NewClient(nil)
		openClient := open.New(conf.Conf.OpenAddress)
		resp, err := openClient.ComponentAccessToken(ctx.Request.Context(), &v1.ComponentAccessTokenRequest{
			Platform: v1.Platform_PLATFORM_WECHAT,
			AppId:    conf.Conf.WechatAppID,
		})
		if err != nil {
			return err
		}
		for _, id := range ids {
			_, err := client.WXA.DeleteTemplate(ctx.Request.Context(), resp.ComponentAccessToken, &wechat.DeleteTemplateRequest{TemplateID: id})
			if err != nil {
				return err
			}
		}
		return nil
	})
	return
}
